package com.raos.xdocreport;

import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * word 生成导出
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2022/2/27 10:42
 */
@RestController
@RequestMapping("/word")
public class WordTestController {

    @GetMapping("/test")
    public void test() throws IOException, XDocReportException {
        generateWord(true, null);
    }

    public void generateWord(boolean tag, HttpServletResponse response) throws IOException, XDocReportException {
        // 获取Word模板，模板存放路径在项目的resources目录下
        InputStream ins = this.getClass().getResourceAsStream("/Word导出模板.docx");

        // 注册xdocreport实例并加载FreeMarker模板引擎
        IXDocReport report = XDocReportRegistry.getRegistry().loadReport(ins, TemplateEngineKind.Freemarker);

        //创建xdocreport上下文对象
        IContext context = report.createContext();

        //创建要替换的文本变量
        context.put("toDateNum", "20220227T00001");
        context.put("dept", "成华区");
        context.put("order", "初次交办");
        context.put("nature", "主办");
        context.put("endDate", "2022-03-01 17:30:00");
        context.put("person", "饶先生");
        context.put("telephone", "15583306348");
        context.put("addr", "武侯区芳草街道");
        context.put("content", "测试来访内容");
        context.put("implDept", "成华区应急局");
        context.put("handler", "罗律师");
        context.put("verdict", "测试结论");
        context.put("approvalOpinion", "测试审批意见");
        context.put("reviewComment", "测试审核意见");
        context.put("remark", "测试备注");

        if (tag) {
            // 输出到本地目录
            FileOutputStream out = new FileOutputStream(new File("D://test//成都市长公开电话办理转办单.docx"));
            report.process(context, out);
        } else {
            //浏览器端下载
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            String fileName = "成都市长公开电话办理转办单.docx";
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            report.process(context, response.getOutputStream());
        }

    }

    @GetMapping("/test2")
    public void test2(HttpServletResponse response) throws IOException, XDocReportException {
        generateWord(false, response);
    }

}
